package xyz.thoughtset.viewer.executor.blocks.utlis;

import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.util.StringUtils;
import xyz.thoughtset.viewer.modules.step.entity.block.BlockBodyEle;
import xyz.thoughtset.viewer.modules.step.entity.block.EleParam;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class BlockArgsUtils {
// new SpelExpressionParser(), new StandardEvaluationContext()
    public static Map filterParams(BlockBodyEle bodyEle, Map contentMap){
        ExpressionParser parser = new SpelExpressionParser();
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setVariables(contentMap);
        return filterParams(false,bodyEle, parser, context);
    }

    public static Map filterParams(BlockBodyEle bodyEle, ExpressionParser parser, StandardEvaluationContext context){
        return filterParams(true, bodyEle, parser, context);
    }

    public static Map filterParams(boolean keyUseId,BlockBodyEle bodyEle, ExpressionParser parser, StandardEvaluationContext context){
        Map tmpParamsMap = new HashMap();
        List<EleParam> params = bodyEle.getParams();
        if (Objects.nonNull(params)){
            for (EleParam blockParam : params){
                if(!StringUtils.hasText(blockParam.getDataExp())){
                    continue;
                }
                String exp =blockParam.getDataExp();
                exp = blockParam.getDataExp().startsWith("#")?exp:"#"+exp;
                Object value = parser.parseExpression(exp).getValue(context);
                String key = keyUseId?blockParam.getParamId():blockParam.getTitle();
                context.setVariable(key, value);
                tmpParamsMap.put(key, value);
            }
        }
        return tmpParamsMap;
    }

}
